package top.aicey.ai.sparring.common.constants;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import top.aicey.ai.sparring.dto.model.BaseResponse;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class ResponseConstants {

    private static void addCors(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
    }

    /**
     * 返回异常响应
     * @param response
     * @param baseResponse
     */
    public static void responseResult(HttpServletResponse response, BaseResponse baseResponse) {
        response.setStatus(HttpStatus.OK.value());
        addCors(response);
        try {
            response.getWriter().write(JSON.toJSONString(baseResponse));
        } catch (IOException ex) {
            log.error("responseErrResult error", ex);
        }
    }
}